﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;

namespace TL_Cloud.Common
{
    /// <summary>
    /// 邮件发送 采用依赖注入的方式
    /// </summary>
    public class MailSender : IMailSender
    {
        private MailConfig mailConfig;
        public ILoggerFactory loggerFactory { get; set; }
        public MailSender(IOptions<MailConfig> Option_MailConfig, ILoggerFactory loggerFactory)
        {
            this.mailConfig = Option_MailConfig.Value;
            this.loggerFactory = loggerFactory;
        }
        public Tuple<bool, string> Sender(string to, string subject, string body)
        {
            return Task.Run<Tuple<bool, string>>(() =>
             {
                 try
                 {
                     var mailhelper = new TL_Cloud.Utils.MailHelper(mailConfig.MailHost, mailConfig.MailPort,
                     mailConfig.MailUserName, mailConfig.MailPassword, mailConfig.MailName);
                     var result = mailhelper.Send(to, subject, body);
                     return new Tuple<bool, string>(result, "");
                 }
                 catch (Exception ex)
                 {
#if DEBUG
                     Trace.WriteLine($"{typeof(MailSender)}出现异常；异常信息为:" + ex.Message);
#endif
                     if (loggerFactory != null)
                     {
                        var logger= loggerFactory.CreateLogger<MailSender>();
                         logger.LogError($"{typeof(MailSender)}出现异常;异常信息为:" + ex.Message + System.Environment.NewLine
                             + $"操作数据：邮件服务器:{mailConfig.MailHost} 发送者:{mailConfig.MailName} 接收者：{to} 端口:{mailConfig.MailPort}");
                     }
                     return new Tuple<bool, string>(false, ex.Message);
                 }
             }).Result;
        }
    }
}
